import { formKey } from '@/constants';
import { isObject } from '@/utils';
import { inject, toRefs } from 'vue';

export const useForm = () => {
  const state = inject(formKey);
  const catchError = err => {
    if (err.code == 1001 && isObject(err.errors)) {
      if (state?.errors) {
        state.errors = err.errors;
      }
    }
  };
  const clearError = () => {
    if (state?.errors) {
      state.errors = {};
    }
  };

  const changeError = key => {
    if (state?.errors) {
      state.errors[key] = null;
    }
  };
  return {
    ...toRefs(state ?? { errors: {} }),
    changeError,
    clearError,
    catchError
  };
};
